jQuery(function($) {

    var selectedProjectKeeper;
    var projectComponents;
    var selectedProjectComponents;

    $('.anchorProject').click(function(event) {
        var anchorId = event.target.id;
        var projectId = anchorId.substring("anchorProject".length);
        $("#tblProjects tr:not(:first)").css("backgroundColor", "white");
        $("#tblProjectComponents tr:not(:first)").remove();
        $("#projectComponentsIds").val("");
        if (selectedProjectKeeper != projectId) {
            selectedProjectKeeper = projectId;
            $("#row" + projectId).css("backgroundColor", "#6699ff");
            $("#projectId").val(projectId);

            $.getJSON(jiraProjectComponentsUrl,
                    {
                        projectId: projectId
                    },
                    function(data) {
                        buildProjectComponentsTable(data.projectComponents);
                        $("#divProjectComponents").show();
                    }
                    );

        } else {
            selectedProjectKeeper = null;
            $("#projectId").val("");
            $("#divProjectComponents").hide();
        }
        return false;
    });

    function buildProjectComponentsTable(projectComponentsArray) {
        $("#tblProjectComponents tr:not(:first)").remove();        
        var content = "";
        projectComponents = projectComponentsArray;
        selectedProjectComponents = new Array();
        for (var i = 0; i < projectComponents.length; i++) {
            var item = projectComponents[i];
            selectedProjectComponents[i] = false;
            content += "<tr id='pcRow" + i + "'>";
            content += "<td>" + item.id + "</td>";
            content += "<td><a href='#' class='anchorProjectComponent' id='anchorProjectComponent" + item.id + "'>" + item.name + "</a></td>";
            content += "</tr>";
        }
        $("#tblProjectComponents").append(content);
        $('.anchorProjectComponent').click(function(event) {
            var anchorId = event.target.id;
            var projectComponentId = anchorId.substring("anchorProjectComponent".length);
            var ids = "";
            for (var i = 0; i < projectComponents.length; i++) {
                var item = projectComponents[i];
                if (projectComponentId == item.id) {
                    var selected = selectedProjectComponents[i];
                    if (selected) {
                        $("#pcRow" + i).css("backgroundColor", "white");
                    } else {
                        $("#pcRow" + i).css("backgroundColor", "#6699ff");
                    }
                    selectedProjectComponents[i] = !selected;
                }
                if (selectedProjectComponents[i]) {
                    ids += item.id + " ";
                }
            }
            $("#projectComponentsIds").val(ids);
         });
    }

});